package top.ibase4j.core.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import top.ibase4j.core.Constants;
import top.ibase4j.core.support.http.HttpCode;
import top.ibase4j.core.support.http.SessionUser;
import top.ibase4j.core.util.CacheUtil;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.FileUtil;
import top.ibase4j.core.util.PropertiesUtil;
import top.ibase4j.core.util.SecurityUtil;
import top.ibase4j.core.util.WebUtil;

/**
 * 签名验证
 * @author ShenHuaJie
 * @since 2018年5月12日 下午10:40:38
 */
public class TokenInterceptor extends BaseInterceptor {
    private SignInterceptor signInterceptor;
    // 白名单
    private List<String> whiteUrls;
    private int size = 0;

    public TokenInterceptor() {
        signInterceptor = new SignInterceptor();
        // 读取文件
        String path = TokenInterceptor.class.getResource("/").getFile();
        whiteUrls = FileUtil.readFile(path + "white/tokenWhite.txt");
        size = null == whiteUrls ? 0 : whiteUrls.size();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        SessionUser session = null;
        // 获取token
        String token = request.getHeader("token");
        if (DataUtil.isNotEmpty(token)) {
            String cacheKey = Constants.TOKEN_KEY + SecurityUtil.encryptMd5(token);
            session = (SessionUser)CacheUtil.getCache().get(cacheKey);
            if (DataUtil.isNotEmpty(session)) {
                request.setAttribute(Constants.CURRENT_USER, session);
                CacheUtil.getCache().expire(cacheKey, PropertiesUtil.getInt("APP-TOKEN-EXPIRE", 60 * 60 * 24 * 7));
            }
        }
        // 请求秘钥的接口不需要签名
        String url = request.getRequestURL().toString();
        String refer = request.getHeader("Referer");
        if (refer != null && refer.contains("/swagger") || WebUtil.isWhiteRequest(url, size, whiteUrls)) {
            logger.info("TokenInterceptor skip");
            if (signInterceptor.preHandle(request, response, handler)) {
                return super.preHandle(request, response, handler);
            }
            return false;
        }
        if (DataUtil.isEmpty(token)) {
            return WebUtil.write(response, HttpCode.UNAUTHORIZED.value(), "请登录");
        }
        logger.debug("Token {}", token);
        // 判断token是否过期
        if (DataUtil.isEmpty(session)) {
            return WebUtil.write(response, HttpCode.UNAUTHORIZED.value(), "会话已过期");
        } else {
            if (signInterceptor.preHandle(request, response, handler)) {
                logger.info("TokenInterceptor successful");
                return super.preHandle(request, response, handler);
            }
            return false;
        }
    }
}
